//
//  TLBrowseCreateManger.m
//  FunnyVideo
//
//  Created by 李鑫 on 15/10/29.
//  Copyright © 2015年 NewEggTech. All rights reserved.
//

#import <AVOSCloud/AVOSCloud.h>
#import "TLBrowseCreateManger.h"



@interface TLBrowseCreateManger ()
@property (nonatomic,strong) NSMutableArray *videoIdQueue;
@end

@implementation TLBrowseCreateManger

+ (TLBrowseCreateManger *)sharedManger{
    static dispatch_once_t onceToken;
    static TLBrowseCreateManger *manger;
    dispatch_once(&onceToken, ^{
    manger = [[TLBrowseCreateManger alloc] init];
    //[TLBrowseCreateManger sharedManger].videoIdQueue = [[NSMutableArray alloc] init];
    });
    
    return manger;
}

- (void)createRandomVideoInfo:(void(^)(TLBrowseVideoInfo *infoLoadedVideoInfo))lessDataLoadedBlock bigDataLoaded:(void(^)(TLBrowseVideoInfo *imageLoadedVideoInfo))bigDataLoadedBlock{
    //Random Video Id
    [self randomVideoId:^(AVObject *v, NSError *error) {
     TLBrowseVideoInfo *videoInfo =  [TLBrowseVideoInfo videoInfoWithVideoObj:v];
    
      [videoInfo startLoadVideoInfo:^(BOOL lessDataLoaded) {
            lessDataLoaded ? lessDataLoadedBlock(videoInfo):nil;
        } bigDataLoad:^(BOOL bigDataLoaded) {
            bigDataLoaded ? bigDataLoadedBlock(videoInfo):nil;
        }];
    }];
}

- (void)randomVideoId:(void(^)(AVObject *v,NSError *error))completion
{
    AVQuery *query = [AVQuery queryWithClassName:@"Video"];
    
    query.limit = 1;
    
    [query addDescendingOrder:@"createdAt"];
    [query addDescendingOrder:@"index"];
    //[query whereKey:@"likes" lessThanOrEqualTo:[NSNumber numberWithInt:200]];
    
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        
        if(!error && objects.count)
        {
            AVObject *obj = [objects lastObject];
            
            int randomIndex= arc4random() % [[obj objectForKey:@"index"] intValue] + 1;
            
            NSLog(@"random index %d",randomIndex);
            
            [query whereKey:@"index" equalTo:[NSNumber numberWithInt:randomIndex]];
            
            [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
                
                if(error)
                    NSLog(@"%@",[error localizedDescription]);
                
                if(objects.count)
                    completion([objects lastObject],error);
            }];
        }
        else
        {
            completion(nil,error);
        }
    }];
}
@end
